<?php

namespace app\tool\controller;

use think\Controller;
use think\facade\Validate;
use think\Image;

/**
 * @title 工具类接口
 */
class Tool extends Controller
{
    /**
     * @title 上传图片
     * @author Leruge
     * @method post
     * @url /tool/upload_img
     *
     * @param name:file type:file require:1 desc:文件
     * @param name:type type:int require:0 default:1 desc:1是图片；2是非图片文件
     * @param name:compress type:int require:0 default:0 desc:1压缩；0不压缩
     *
     * @return url:文件路径不带域名
     */
    public function uploadImg()
    {
        $data = [
            'file' => empty($_FILES['file']['tmp_name']) ? '' : input('file.file'),
            'type' => input('type', 1),
            'compress' => input('compress', 0)
        ];
        if ($data['type'] == 2) {
            $validate = Validate::make([
                'file|文件' => 'require|file',
                'type|文件类型' => 'require|in:1,2',
                'compress|压缩' => 'require|in:0,1'
            ]);
        } else {
            $validate = Validate::make([
                'file|图片' => 'require|file|fileExt:gif,jpg,jpeg,bmp,png,swf',
                'type|文件类型' => 'require|in:1,2',
                'compress|压缩' => 'require|in:0,1'
            ]);
        }
        if (!$validate->check($data)) {
            $this->result('', 0, $validate->getError(), 'json');
        } else {
            $savePath = env('root_path') . 'public/uploads/';
            if (!$savePath) {
                mkdir($savePath, 0777, true);
            }
            if ($data['compress'] == 0) {
                $info = $data['file']->move($savePath);
                $url = '/uploads/' . $info->getSaveName();
                $url = str_replace('\\', '/', $url);
            } else {
                if ($data['type'] == 1) {
                    $saveName = uniqid() . '.jpg';
                    $image = Image::open($data['file']);
                    $image->save($savePath . $saveName, 'jpg', 10, true);
                    $url = '/uploads/' . $saveName;
                } else {
                    $info = $data['file']->move($savePath);
                    $url = '/uploads/' . $info->getSaveName();
                    $url = str_replace('\\', '/', $url);
                }
            }
            return $this->result(['url' => $url], 1, 'success', 'json');
        }
    }
}
